﻿using System;
using System.IO;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.SqlClient;
using System.Data.Common;

public partial class LoginPasswordDetail : System.Web.UI.Page
{
    Microsoft.Practices.EnterpriseLibrary.Data.Database db = DatabaseFactory.CreateDatabase("Application_Data");

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Convert.ToBoolean(Session["sAdministrator"].ToString()) == false)
            {
                Response.Redirect("~/AccessDenied.aspx");
            }

            this.btnDelete.Attributes.Add("OnCLick", "return confirm('Are you sure you want to delete this Login/Password?');");

            BindData();
        }
    }
    private void BindData()
    {
        DbCommand dbCommand1 = db.GetSqlStringCommand("OPEN SYMMETRIC KEY PrivateDataKey DECRYPTION BY CERTIFICATE PrivateDataCertificate SELECT [Login],[Description],CONVERT(NVARCHAR(500),DECRYPTBYKEY(EncryptedPassword)) AS UnEncryptedPassword FROM LoginPassword WHERE Login = '" + Request.QueryString["Login"].ToString() + "' CLOSE SYMMETRIC KEY PrivateDataKey;");

        DataSet ds1 = db.ExecuteDataSet(dbCommand1);
        DataRow dr1 = ds1.Tables[0].Rows[0];

        this.txtLogin.Text = dr1["Login"].ToString();
        this.txtDescription.Text = dr1["Description"].ToString();
        this.txtPassword.Text = dr1["UnEncryptedPassword"].ToString();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        DbCommand dbCommand = db.GetSqlStringCommand("DELETE FROM LoginPassword WHERE Login = '" + Request.QueryString["Login"].ToString() + "'");

        db.ExecuteNonQuery(dbCommand);

        MessageBox.Show("Login/Password Deleted.");

        Response.Redirect("~/LoginPasswordList.aspx");
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        DbCommand dbCommand = db.GetSqlStringCommand("iuLoginPassword " +
                                           "@Login = '" + this.txtLogin.Text + "'," +
                                           "@Description = '" + this.txtDescription.Text + "'," +
                                           "@Password = '" + this.txtPassword.Text + "'");

        db.ExecuteNonQuery(dbCommand);

        MessageBox.Show("Login/Password Updated Successfully.");

        Response.Redirect("~/LoginPasswordList.aspx");
    }
}
